<template>
  <el-row :gutter="20" justify="space-between">
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <el-card shadow="never" class="mt-5px" style="height: 418px">
        <el-skeleton :loading="loading" animated>
          <div class="mb-3">
            <el-text class="!text-xl font-bold">外汇牌价/世界时间</el-text>
          </div>
          <el-card shadow="hover" class="mb-10px">
            <el-skeleton :loading="loading" animated>
              <div style="width: 100%; display: flex; justify-content: center">
                <el-select
                  v-model="fromCurrency"
                  filterable
                  :clearable="false"
                  class="mr-10"
                  @change="convertCurrency"
                >
                  <template #label="{ label }">
                    <div style="display: flex">
                      <Icon
                        v-if="currencys && label"
                        :icon="currencys.find((obj) => obj.label === label)?.icon"
                        style="margin-right: 3px; margin-top: 3px"
                      />
                      <span>{{ label }}</span>
                    </div>
                  </template>
                  <el-option
                    v-for="currency in currencys"
                    :key="currency.value"
                    :label="currency.label"
                    :value="currency.value"
                  >
                    <div class="flex items-center">
                      <Icon :icon="currency.icon" class="mr-1" />
                      <span>{{ currency.label }}</span>
                    </div>
                  </el-option>
                </el-select>

                <el-select v-model="toCurrency" :clearable="false" @change="convertCurrency">
                  <template #label="{ label }">
                    <div style="display: flex">
                      <Icon
                        v-if="currencys && label"
                        :icon="currencys.find((obj) => obj.label === label)?.icon"
                        class="mr-1"
                        style="margin-right: 3px; margin-top: 3px"
                      />
                      <span>{{ label }}</span>
                    </div>
                  </template>
                  <el-option label="人民币" value="CNY">
                    <div class="flex items-center">
                      <Icon icon="flag:cn-4x3" class="mr-1" />
                      <span>人民币</span>
                    </div>
                  </el-option>
                  <el-option label="美元" value="USD">
                    <div class="flex items-center">
                      <Icon icon="flag:us-4x3" class="mr-1" />
                      <span>美元</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
              <div class="mt-2" style="width: 100%; display: flex; justify-content: center">
                <div style="width: 280px; text-align: center" class="!text-3xl font-bold">
                  <strong>100</strong>
                </div>
                <div style="width: 280px; text-align: center" class="!text-3xl font-bold">
                  <strong> {{ toCurrencyMoney }}</strong>
                </div>
              </div>
            </el-skeleton>
          </el-card>
          <el-card shadow="hover" class="mb-10px">
            <el-skeleton :loading="loading" animated>
              <div style="display: flexbox">
                <el-select v-model="selectedTimeZone" placeholder="请选择时区" @change="updateTime">
                  <el-option
                    v-for="zone in timeZones"
                    :key="zone.offset"
                    :label="`${zone.name}: ${zone.cities.join(', ')}`"
                    :value="zone.offset"
                  />
                </el-select>

                <!-- 当前时区的时间显示 -->
                <div class="!text-2xl font-bold mt-5">
                  <strong>{{ currentTime }}</strong>
                </div>
              </div>
            </el-skeleton>
          </el-card>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <el-card shadow="never" class="mt-5px">
        <div class="mb-3">
          <el-text class="!text-xl font-bold">邮件收发情况</el-text>
          <el-select
            v-model="receiveSendParams.ownerIds"
            placeholder="人员"
            :clearable="true"
            multiple
            class="mr-2 ml-4"
            @change="handleReceiveSendChange"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
          <el-date-picker
            v-model="receiveSendParams.statisticsTime"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            @change="handleReceiveSendChange"
          />
        </div>
        <el-skeleton :loading="loading" animated>
          <el-card shadow="hover" class="mb-10px">
            <el-skeleton :loading="loading" animated>
              <Echart :options="receiveSendData" :height="280" />
            </el-skeleton>
          </el-card>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20" justify="space-between" class="mt-25px">
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <el-card shadow="never" class="mt-5px">
        <div class="mb-3">
          <el-text class="!text-xl font-bold">客户关键行为趋势</el-text>
          <el-select
            v-model="keyTrendParams.ownerIds"
            placeholder="人员"
            :clearable="true"
            multiple
            class="mr-2 ml-4"
            @change="handleKeyTrendChange"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
          <el-date-picker
            v-model="keyTrendParams.statisticsTime"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            @change="handleKeyTrendChange"
          />
        </div>
        <el-skeleton :loading="loading" animated>
          <el-card shadow="hover" class="mb-10px">
            <el-skeleton :loading="loading" animated>
              <Echart :options="keyTrendData" :height="280" />
            </el-skeleton>
          </el-card>
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
      <el-card shadow="never" class="mt-5px">
        <div class="mb-3">
          <el-text class="!text-xl font-bold">客户成交转化率</el-text>
          <el-select
            v-model="dealConvertParams.ownerIds"
            placeholder="人员"
            :clearable="true"
            multiple
            class="mr-2 ml-4"
            @change="handleDealConvertChange"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </div>
        <el-skeleton :loading="loading" animated>
          <el-card shadow="hover" class="mb-10px">
            <el-skeleton :loading="loading" animated>
              <Echart :options="dealConvertData" :height="280" />
            </el-skeleton>
          </el-card>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>
</template>
<script setup lang="ts" name="Home">
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import * as StatisticsMailApi from '@/api/statistics/statisticsMail'
import * as StatisticsCustomerApi from '@/api/statistics/statisticsCustomer'
import * as InfraRateApi from '@/api/infra/data/rate'
import * as UserApi from '@/api/system/user/user'
import { formatDate, betweenDay } from '@/utils/formatTime'
const userList = ref<UserApi.UserVO[]>([])
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
const message = useMessage() // 消息弹窗
import type { WorkplaceTotal } from './types'
import {
  receiveSendOptions,
  dealConvertOptions,
  keyTrendOptions,
  timeZones,
  currencys
} from './indexData'

const loading = ref(true)
const fromCurrency = ref('USD')
// const toCurrency = ref('CNY')
const toCurrency = ref('CNY')
const receiveSendParams = ref({
  ownerIds: [],
  statisticsTime: [
    formatDate(new Date(), 'YYYY-MM-01 00:00:00'),
    formatDate(new Date(), 'YYYY-MM-DD 23:59:59')
  ] as any
})

const dealConvertParams = ref({
  ownerIds: []
})

const keyTrendParams = ref({
  ownerIds: [],
  statisticsTime: [
    formatDate(new Date(), 'YYYY-MM-01 00:00:00'),
    formatDate(new Date(), 'YYYY-MM-DD 23:59:59')
  ] as any
})

const receiveSendData = reactive<EChartsOption>(receiveSendOptions) as EChartsOption
const dealConvertData = reactive<EChartsOption>(dealConvertOptions) as EChartsOption
const keyTrendData = reactive<EChartsOption>(keyTrendOptions) as EChartsOption

const currencyRateData = ref()
const toCurrencyMoney = ref('0')
let timer: any = null
let rater: any = null

const init = async () => {
  userList.value = await UserApi.getOwnerUser()
  await Promise.all([getCount(), getReceiveSendData(), getDealConvertData(), getKeyTrendData()])
  loading.value = false
}

// 定义时区数据

// 绑定选中的时区偏移量，默认为东八区 (offset: 8)
const selectedTimeZone = ref(8)

// 当前时区时间
const currentTime = ref('')

// 更新时间函数
const updateTime = () => {
  const now = new Date()
  const utcTime = now.getTime() + now.getTimezoneOffset() * 60 * 1000 // 转换为 UTC 时间
  const localTime = utcTime + selectedTimeZone.value * 60 * 60 * 1000 // 根据时区偏移量计算本地时间
  const localDate = new Date(localTime)
  dayjs.locale('zh-cn')
  currentTime.value = dayjs(localDate).format('MM月DD日 dddd HH:mm:ss ') // 格式化为可读时间
}

const getCurrencyRate = async () => {
  currencyRateData.value = await InfraRateApi.listQuery()
}

onMounted(async () => {
  await init()
  updateTime() // 初始化时间
  timer = setInterval(updateTime, 1000) // 每秒更新一次
  await getCurrencyRate()
  convertCurrency()
  rater = setInterval(getCurrencyRate, 1000 * 60 * 60) // 每小时更新一次
})

onUnmounted(() => {
  clearInterval(timer) // 组件卸载时清除定时器
  clearInterval(rater) // 组件卸载时清除定时器
})

const convertCurrency = () => {
  if (toCurrency.value == 'CNY') {
    let cnyRate = 0
    currencyRateData.value.forEach((data) => {
      if (data.currency == 'CNY') cnyRate = data.rate
    })

    currencyRateData.value.forEach((data) => {
      if (data.currency == fromCurrency.value)
        toCurrencyMoney.value = ((100 / data.rate) * cnyRate).toFixed(4)
    })
  } else {
    currencyRateData.value.forEach((data) => {
      if (data.currency == fromCurrency.value) toCurrencyMoney.value = (100 / data.rate).toFixed(4)
    })
  }
}

// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

const getReceiveSendData = async () => {
  const queryData = await StatisticsMailApi.receiveSendQuery(receiveSendParams.value)

  const xData = generateDateRange(receiveSendParams.value.statisticsTime)

  const series = receiveSendConvertSeries(xData, queryData)

  set(receiveSendData, 'xAxis.data', xData)
  set(receiveSendData, 'series', series)
}
const handleReceiveSendChange = async () => {
  checkStatisticsTime(receiveSendParams)
  await getReceiveSendData()
}

const receiveSendConvertSeries = (xData, queryData) => {
  let seriesData = {}
  xData.forEach((data) => {
    seriesData[data] = { receiveCount: 0, oneSendCount: 0, manySendCount: 0 }
  })

  queryData.forEach((data) => {
    data.manySendCount = data.sendCount - data.oneSendCount
    seriesData[formatDate(data.statisticsTime, 'MM-DD')].receiveCount += data.receiveCount
    seriesData[formatDate(data.statisticsTime, 'MM-DD')].oneSendCount += data.oneSendCount
    seriesData[formatDate(data.statisticsTime, 'MM-DD')].manySendCount += data.manySendCount
  })

  let series = [
    {
      name: '已发送邮件',
      type: 'bar',
      emphasis: {
        focus: 'series'
      },
      data: Object.values(seriesData).map((data: any) => data.receiveCount)
    },
    {
      name: '一对一发送邮件',
      type: 'bar',
      stack: '发送邮件',
      emphasis: {
        focus: 'series'
      },
      data: Object.values(seriesData).map((data: any) => data.oneSendCount)
    },
    {
      name: '一对多发送邮件',
      type: 'bar',
      stack: '发送邮件',
      emphasis: {
        focus: 'series'
      },
      data: Object.values(seriesData).map((data: any) => data.manySendCount)
    }
  ]
  return series
}

const generateDateRange = (statisticsTime): string[] => {
  const startDate = new Date(statisticsTime[0])
  const endDate = new Date(statisticsTime[1])

  const dateArray: string[] = []

  let currentDate = startDate
  while (currentDate <= endDate) {
    dateArray.push(formatDate(currentDate, 'MM-DD'))
    currentDate = new Date(currentDate.setDate(currentDate.getDate() + 1))
  }

  return dateArray
}

const handleDealConvertChange = async () => {
  await getDealConvertData()
}

const getDealConvertData = async () => {
  const queryData = await StatisticsCustomerApi.dealConvertQuery(dealConvertParams.value)

  const xData = queryData.map(
    (data) => userList.value.find((obj) => obj.id === data.ownerId)?.nickname
  )

  let series = [
    {
      name: '转化率',
      type: 'bar',
      emphasis: {
        focus: 'series'
      },

      data: queryData.map((data: any) => ((data.dealCount / data.totalCount) * 100).toFixed(2))
    }
  ]
  set(dealConvertData, 'xAxis.data', xData)
  set(dealConvertData, 'series', series)
}

const handleKeyTrendChange = async () => {
  checkStatisticsTime(keyTrendParams)
  await getKeyTrendData()
}

const checkStatisticsTime = (params) => {
  if (params.value.statisticsTime && params.value.statisticsTime.length == 2) return
  const diffDay = betweenDay(params.value.statisticsTime[0], params.value.statisticsTime[1])
  if (diffDay > 31) {
    message.error('时间不能超过一个月')
    params.value.statisticsTime = [
      formatDate(new Date(), 'YYYY-MM-01 00:00:00'),
      formatDate(new Date(), 'YYYY-MM-DD 23:59:59')
    ]
  }
}

const getKeyTrendData = async () => {
  const queryData = await StatisticsCustomerApi.keyTrendQuery(keyTrendParams.value)
  const xData = generateDateRange(keyTrendParams.value.statisticsTime)

  const series = keyTrendConvertSeries(xData, queryData)

  set(keyTrendData, 'xAxis.data', xData)
  set(keyTrendData, 'series', series)
}

const keyTrendConvertSeries = (xData, queryData) => {
  let seriesData = {}
  xData.forEach((data) => {
    seriesData[data] = { createCount: 0, followCount: 0 }
  })

  queryData.forEach((data) => {
    data.manySendCount = data.sendCount - data.oneSendCount
    seriesData[formatDate(data.statisticsTime, 'MM-DD')].createCount += data.createCount
    seriesData[formatDate(data.statisticsTime, 'MM-DD')].followCount += data.followCount
  })

  let series = [
    {
      name: '新建客户数', // 系列名称
      data: Object.values(seriesData).map((data: any) => data.createCount), // 数据
      type: 'line', // 类型为折线图
      smooth: false, // 平滑曲线
      itemStyle: {
        color: '#4CAF50' // 自定义线条颜色
      }
    },
    {
      name: '跟进客户数', // 系列名称
      data: Object.values(seriesData).map((data: any) => data.followCount), // 数据
      type: 'line', // 类型为折线图
      smooth: false, // 平滑曲线
      itemStyle: {
        color: '#FF9800' // 自定义线条颜色
      }
    }
  ]
  return series
}
</script>
